<?php

/**
 * Controller for grid element with table data.
 * Contains CRUD operations
 */
class TablegridController extends Zend_Controller_Action
{

    public function init()
    {
        $this->_helper->viewRenderer->setNoRender();
        $this->_helper->getHelper('layout')->disableLayout();
    }

    /**
     * Get table data by data base and table names
     */
    public function readAction()
    {

        $dataBase = new Default_Model_AbstractDatabase();

        $dataBaseName = $this->_getParam('databaseName');
        $tableName = $this->_getParam('tableName');

        $tableData = $dataBase->getTableData(
                $dataBaseName,
                $tableName
        );

        /**
         * If column is a primary key, then column is not editable
         */
        $primaryKeyFlag = false;
        $primaryKey = $dataBase->getPrimaryKeyOfTabel($dataBaseName, $tableName);
        if ($primaryKey) {
            $primaryKeyFlag = true;
        }

        // Initialize return array for grid element
        $formatedTableData = array(
                'metaData' => array(
                    'idProperty' => $primaryKey,
                    'root' => 'records',
                    'totalProperty' => 'total',
                    'successProperty' => 'success',
                    'fields' => array()
                ),
                'success' => true,
                'total' => 50,
                'records' => array(),
                'columns' => array()
            );


        $rowData = array();

        foreach ($tableData as $row) {
            foreach ($row as $column => $value) {
                // Create fields and columns for grid
                if ( count($formatedTableData['metaData']['fields']) != count($row) ) {
                    $formatedTableData['metaData']['fields'][] = array(
                        'name' => $column,
                        'type' => 'auto',
                    );

                    if ( $column == $primaryKey ) {
                        $formatedTableData['columns'][] = array(
                            'header' => $column,
                            'dataIndex' => $column,
                            'sortable' => true,
                            'primary' => $primaryKeyFlag
                        );
                        $primaryKeyFlag = false;
                    } else {
                        $formatedTableData['columns'][] = array(
                            'header' => $column,
                            'dataIndex' => $column,
                            'sortable' => true,
                            'primary' => $primaryKeyFlag
                        );
                    }

                }
                // Store row data
                $rowData[$column] = $value;
            }

            // Record stored row data into return array
            $formatedTableData['records'][] = $rowData;
            unset($rowData);
        }

        echo Zend_Json_Encoder::encode($formatedTableData);

    }

    /**
     * Create row in table
     */
    public function createAction()
    {
        // Get row data
        $rowData = Zend_Json::decode($this->_getParam('undefined'));
        $dataBaseName = $this->_getParam('databaseName');
        $tableName = $this->_getParam('tableName');

        $rowColumns = array();
        $columnsValues = array();
        unset($rowData['id']);
        
        $dataBase = new Default_Model_AbstractDatabase();
        $result = $dataBase->createRow($rowData, $dataBaseName, $tableName);

        $responce = array(
            'success' => '',
            'message' => '',
            'records' => array()
        );

        if ( $result ) {
            $responce['success'] = true;
            $responce['message'] = 'Create record';
            $responce['records'][$result['name']] = $result['value'];
            foreach ($rowData as $column => $value) {
                $responce['records'][$column] = $value;
            }

        }

        echo Zend_Json_Encoder::encode($responce);

    }

    /**
     * Delete row from table
     */
    public function deleteAction()
    {
        // Get row data
        $rowData = Zend_Json::decode($this->_getParam('undefined'));
        $dataBaseName = $this->_getParam('databaseName');
        $tableName = $this->_getParam('tableName');
        
        $dataBase = new Default_Model_AbstractDatabase();
        
        $result = $dataBase->deleteRow($rowData, $dataBaseName, $tableName);

        $responce = array(
            'success' => ''
        );

        if ( $result ) {
            $responce['success'] = true;
        };

        echo Zend_Json_Encoder::encode($responce);

    }

    /**
     * Update the row in table
     */
    public function updateAction()
    {
        
    }
}